package cn.zhangmh.easymvp.books;

import android.content.Context;
import android.util.Log;

import cn.zhangmh.easymvp.Presenter;
import cn.zhangmh.easymvp.books.entity.Books;
import cn.zhangmh.easymvp.View;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by zmh on 2017/4/30.
 */

public class BookPresenter implements Presenter {

    private BooksService  booksService;
    private Context context;
    private BookView bookView;
    private Books mBook;

    public  BookPresenter(Context mContext){
        this.context = mContext;
    }

    @Override
    public void onCreate() {
        booksService = new BooksService(context);
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {

    }

    @Override
    public void pause() {

    }

    /**
     * 指定当前操作的view
     * @param view
     */
    @Override
    public void attachView(View view) {
        bookView =  (BookView) view;
    }

    /**
     * 发起数据请求，并通过可观察对象实现跨线程数据更新
     * @param name
     * @param tag
     * @param start
     * @param count
     */
    public void   getSearchBooks(String name,String tag ,int start ,int count){
        booksService.getSearchBooks(name, tag, start, count)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Books>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Books book) {
                        mBook = book;
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mBook == null )
                            bookView.onError("请求数据失败");
                    }

                    @Override
                    public void onComplete() {
                        bookView.onSuccess(mBook);
                        if (null == mBook){
                        Log.d("数据请求未返回有效结果", "onComplete: ");
                    }

                    }
                });
    }
}
